package com.s64.ch08.modules.security;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.s64.ch08.entity.Menu;
import com.s64.ch08.entity.Role;
import com.s64.ch08.entity.User;
import com.s64.ch08.service.IMenuService;
import com.s64.ch08.service.IRoleService;
import com.s64.ch08.service.IUserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class UserDetailsServiceImpl implements UserDetailsService {
    private final IUserService userService;
    private final IRoleService roleService;
    private final IMenuService menuService;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        //1.根据登录名查询用户
        User user = userService.getOne(Wrappers.lambdaQuery(User.class).eq(User::getUserName, username));
        if (user == null) throw new UsernameNotFoundException("用户不存在");
        //2.查询用户对应的角色
        List<Role> roleList = roleService.listByUserId(user.getUserId());
        //3.查询角色对应的权限
        List<Menu> menuList = menuService.listByUserId(user.getUserId());

        LoginUser loginUser = new LoginUser();
        loginUser.setRoleKeyList(roleList.stream().map(Role::getRoleKey).collect(Collectors.toSet()));
        loginUser.setPermsList(menuList.stream().map(Menu::getPerms).collect(Collectors.toSet()));
        loginUser.setUser(user);
        return loginUser;
    }
}
